package com.xiongwei.io;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * ZipInputStream可以读取zip格式的流，ZipOutputStream可以把多份数据写入zip包；
 *
 * 配合FileInputStream和FileOutputStream就可以读写zip文件。
 *
 * @author XiongWei
 * @date 2021/1/8
 */
public class ZipIOUse {

    public static void main(String[] args) {

    }

    /**
     * 读取zip包
     */
    public void readZip() {
        try (ZipInputStream is = new ZipInputStream(new FileInputStream("/Users/apple/Downloads/love-master.zip"))) {
            ZipEntry entry = null;
            while ((entry = is.getNextEntry()) != null) {
                String name = entry.getName();
                if (!entry.isDirectory()) {
                    int n;
                    while ((n = is.read()) != -1) {
                        //...
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入zip包
     * 如果要实现目录层次结构，new ZipEntry(name)传入的name要用相对路径。
     */
    public void writeZip() {
        try (ZipOutputStream os = new ZipOutputStream(new FileOutputStream("/Users/apple/Downloads/love-master.zip"))) {
            File[] files = new File[1];
            for (File file : files) {
                os.putNextEntry(new ZipEntry(file.getName()));
                os.write(getFileDataAsBytes(file));
                os.closeEntry();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private byte[] getFileDataAsBytes(File file) throws IOException {
        byte[] bb = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file.getAbsoluteFile());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int n;
        while ((n = fis.read(bb)) != -1) {
            baos.write(bb, 0, n);
        }
        fis.close();
        baos.close();
        return baos.toByteArray();
    }
}
